<?php
namespace app\web\controller;

use app\model\Util; 
use app\model\Theme; 
use app\model\Game as Game_mod;

class Game extends Base
{
    public function Game()
    {
/**
 * Created by 易宣软件
 * Desc:定制分享游戏
 * User:cbw
 * Date: 2021/1/5
 */

global $_G,$_P;
$params = $_P;
$do = 'game';
$ac = !empty($params['op'])?$params['op']:'level';
$themeid = isset($params['themeid'])?$params['themeid']:'';//活动id
if($themeid <= 0){
    $themeid = Theme::getDefaultThemenew();
}

$themelist =  Game_mod::getThemeListByType('lz_game',0);
$themelist = $themelist['type_theme_list'];
if(count($themelist)==1){
    if ($themeid != $themelist[0]['id']){
        $url =   $_G['siteroot'].createWebUrl($do,array("themeid"=>$themelist[0]['id'],'op'=>$ac));
        echo "<script language='javascript' type='text/javascript'>";
        echo "window.location.href='$url';";
        echo "</script>";
        exit;
    }
}


if (empty($_P['createtime']['start'])){
    $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
    $start_day =  date('Y-m-d',$start_day);
}else{
    $start_day =  $_P['createtime']['start'];
}
$end_day = empty($_P['createtime']['end']) ? date('Y-m-d',TIMESTAMP): $_P['createtime']['end'] ;

$theme = Theme::getThemeById($themeid);
if (!$theme){
    $response = modelShow(40002);
    return_msg($response, '', 'ajax');
}

$config =   Theme::getConfig($themeid);
$system= $_G['system'];
$page_index = max(1,intval($params['page']));
$page_size = 10;
$page_start = ($page_index-1)*$page_size;
$response = modelShow(40000);

if ($ac =='detail'){
    $uid = $_P['uid'];
    $page_size=10;
//    $page_total = Game_mod::getGameLifeCount($themeid,$uid);
    $type = trim($_P['type']);
    $list = Game_mod::formatLifeInfo($themeid,$uid,$page_start,$page_size,$type);
    $page_total = $list['total'];
    $share_total = Game_mod::getGameLifeCount($themeid,$uid,'share');

    $pager = pagination($page_total,$page_index,$page_size);
    $return_clicent = get_defined_vars();
return view('/game/level/detail_list', $return_clicent);
    exit;
}

//关卡
if ($ac=='level'){
    $page_total = Game_mod::getGameCount($themeid);
    $list = Game_mod::getGameList($themeid,'',$page_start,$page_size);
    $return_clicent = get_defined_vars();
return view('/game/level/list', $return_clicent);
}elseif ($ac=='level_add'){
    $box_prizes = Game_mod::getGamePrizeList($themeid,'','level');
    $return_clicent = get_defined_vars();
return view('/game/level/edit', $return_clicent);
}elseif ($ac=='level_edit'){
    $total = Game_mod::getGameCount($themeid);
    $list = Game_mod::getGameList($themeid,'',$page_start,$page_size);
    $gl_id = $params['gl_id'];
    $item = Game_mod::getGameItemById($gl_id);
    $box_prizes = Game_mod::getGamePrizeList($themeid,'','level');
    $return_clicent = get_defined_vars();
return view('/game/level/edit', $return_clicent);
}elseif ($ac=='level_update'){
    $sorts = Game_mod::formatLevelBySorts($params['level_sorts']);
    $gl_id = $params['gl_id'];
    $type = $params['type'];
    $open_question = $params['open_question'];
    $type_op_num = $params['type_op_num'];
    $p_id = $params['p_id'];
    $sort = $params['sort'];
    $img = $params['img'];
    $data = [
        'type'=>$type,
        'type_op_num'=>$type_op_num,
        'p_id'=>$p_id,
        'sort'=>$sort,
        'bind_show_sorts'=>$sorts,
        'icon'=>tomedia(str_replace('/99.jpg','/logo.jpg',$img)),
        'themeid'=>$themeid,
        'open_question'=>$open_question,
    ];
    $has_sort = Game_mod::getGameCount($themeid,'',$sort);
    if (!$gl_id && $has_sort>=1){
        $response = modelShow(30000,'该关卡已存在，请勿重复添加同一关卡');
        return_msg($response, '', 'ajax');
        return;
    }
    if (!$gl_id){
        $res = Game_mod::insertGame($data);//新增
    }else{

        $where = ['gl_id'=>$gl_id];//更新
        $res = Game_mod::editGameByWhere($where,$data);
    }
    if (!$res){
        $response = modelShow(30000);
    }else{
        $response = modelShow(200);
    }
    return_msg($response, '', 'ajax');
}elseif ($ac=='list_del'){
    $l_id = $params['l_id'];
    if ($l_id>7){
        $res = Game_mod::delKoiItemById($l_id,$themeid);
        if (!$res){
            $response = modelShow(30000);
        }else{
            $response = modelShow(200);
        }
        return_msg($response, '', 'ajax');
    }
}

//宝箱
if ($ac=='box_list'){
    $page_total = Game_mod::getGameBoxCount($themeid);
    $list = Game_mod::getGameBoxList($themeid,'',$page_start,$page_size);
    $pager = pagination($page_total,$page_index,$page_size);
    $return_clicent = get_defined_vars();
return view('/game/box/box', $return_clicent);
}elseif ($ac=='box_add'){
    $box_prizes = Game_mod::getGamePrizeList($themeid,'','box');
    $return_clicent = get_defined_vars();
return view('/game/box/edit', $return_clicent);
}elseif ($ac=='box_edit'){
    $gb_id = $params['gb_id'];
    $item = Game_mod::getGameBoxItemById($themeid,$gb_id);
    $box_prizes = Game_mod::getGamePrizeList($themeid,'','box');
    $return_clicent = get_defined_vars();
return view('/game/box/edit', $return_clicent);
}elseif ($ac=='box_update'){
    $gb_id = $params['gb_id'];
    $themeid = $themeid;
    $name = $params['name'];
    $type = $params['type'];
    $default = Game_mod::getGameBoxByType($themeid,0);
    $shares = Game_mod::getGameBoxByType($themeid,1);
    if ($type==1){
        $new_total = $shares+1;
    }elseif ($type==0){
        $new_total = $default+1;
    }
    if ($new_total>3){
        $response = modelShow(30001);
        return_msg($response, '', 'ajax');
    }
    $friend_view = $params['friend_view'];
    $open_tips = isset($params['open_tips'])?$params['open_tips']:'恭喜您，获得';
    $p_id = $params['p_id'];
    $data = [
        'themeid'=>$themeid,
        'name'=>$name,
        'open_tips'=>$open_tips,
        'p_id'=>$p_id,
        'type'=>$type,
        'friend_view'=>$friend_view,
    ];
    if (!$gb_id){
        $res = Game_mod::insertGameBox($data);
    }else{
        $where = ['gb_id'=>$gb_id];
        $res = Game_mod::editGameBoxByWhere($where,$data);
    }
    if (!$res){
        $response = modelShow(30000);
    }else{
        $response = modelShow(200);
    }
    return_msg($response, '', 'ajax');
}

//奖项列表
if ($ac=='prize_list'){
    $page_total = Game_mod::getGamePrizeCount($themeid);
    $list = Game_mod::getGamePrizeList($themeid,'','',$page_start,$page_size);
    $pager = pagination($page_total,$page_index,$page_size);
    $return_clicent = get_defined_vars();
return view('/game/prize/prize', $return_clicent);
}elseif ($ac=='prize_add'){
    $return_clicent = get_defined_vars();
return view('/game/prize/edit', $return_clicent);
}elseif ($ac=='prize_edit'){
    $p_id = $params['p_id'];
    $item = Game_mod::getGamePrizeItemById($p_id);
    $return_clicent = get_defined_vars();
return view('/game/prize/edit', $return_clicent);
}elseif ($ac=='prize_update'){
    $p_id = $params['p_id'];
    $name = $params['name'];
    $type = $params['type'];
    $small_img = $params['small_img'];
    $data = [
        'name'=>$name,
        'type'=>$type,
        'img'=>tomedia(str_replace('/99.jpg','/logo.jpg',$small_img)),
        'themeid'=>$themeid
    ];
    if (!$p_id){
        $res = Game_mod::insertGamePrize($data);
    }else{
        $where = ['p_id'=>$p_id];
        $res = Game_mod::editGamePrizeByWhere($where,$data);
    }
    if (!$res){
        $response = modelShow(30000);
    }else{
        $response = modelShow(200);
    }
    return_msg($response, '', 'ajax');
}

//宝箱问题库
if ($ac=='question_list'){
    $page_total = Game_mod::getGameQuestionCount($themeid,'');
    $list = Game_mod::getGameQuestionList($themeid,'',$page_start,$page_size);
    $pager = pagination($page_total,$page_index,$page_size);
    $return_clicent = get_defined_vars();
return view('/game/question/question', $return_clicent);
}elseif ($ac=='question_add'){
    $return_clicent = get_defined_vars();
return view('/game/question/edit', $return_clicent);
}elseif ($ac=='question_edit'){
    $q_id = $params['q_id'];
    $item = Game_mod::getGameQuestionItemById($q_id);
    $return_clicent = get_defined_vars();
return view('/game/question/edit', $return_clicent);
}elseif ($ac=='question_update'){
    $q_id = $params['q_id'];
    $question = trim($params['question']);
    $first = trim($params['first']);
    $second = trim($params['second']);
    $third = trim($params['third']);
    $sure_method = $params['sure_method'];
    $data = [
        'question'=>$question,
        'first'=>$first,
        'second'=>$second,
        'third'=>$third,
        'sure_method'=>$sure_method,
        'themeid'=>$themeid
    ];
    if (!$q_id){
        $res = Game_mod::insertGameQuestion($data);
    }else{
        $where = ['q_id'=>$q_id];
        $res = Game_mod::editGameQuestionByWhere($where,$data);
    }
    if (!$res){
        $response = modelShow(30000);
    }else{
        $response = modelShow(200);
    }
    return_msg($response, '', 'ajax');
}

//用户游戏关卡
if ($ac=='user_level' || $ac=='user_level_search' || $ac=='user_box' || $ac=='user_box_search') {
    $box_user_list = Game_mod::formatBoxUserList($themeid);
    //获取所有的关卡以及对应的数量
    $level_user_list = Game_mod::formatLevelUserList($themeid);
    $gl_id = isset($_P['gl_id'])?$_P['gl_id']:'';
    $gb_id = isset($_P['gb_id'])?$_P['gb_id']:'-1';
    if ($ac=='user_level' && $params['search_data']){
        $ac='user_level_search';
    }
}
if ($ac=='user_level'){
//    yxlog('排查日志:[方法'.$ac.'[参数：'.json_encode($params).'-宝箱类型:'.json_encode($box_user_list));
//    $total = Game_mod::getGameUserLevelList($themeid,0);
    $total = Game_mod::getLevelUserFlag($themeid,'',$start_day,$end_day,0,0);
    $list = Game_mod::getLevelUserFlag($themeid,'',$start_day,$end_day,$page_start,$page_size,$gl_id);
    $page_total = count($total);
    $pager = pagination($page_total,$page_index,$page_size);
    $return_clicent = get_defined_vars();
return view('/game/level/user_list', $return_clicent);
}elseif ($ac=='user_level_search'){
//    yxlog('排查日志:[方法'.$ac.'[参数：'.json_encode($params).'-宝箱类型:'.json_encode($box_user_list));
    $level_user_list = Game_mod::formatLevelUserList($themeid);
    $gl_id = isset($_P['gl_id'])?$_P['gl_id']:'';

    $search_data = isset($params['search_data'])?$params['search_data']:'';
    if ($search_data){
        $search_data = '%'.$search_data.'%';
    }
    $lists = Game_mod::getLevelUserFlag($themeid,$search_data,$start_day,$end_day,0,0,$gl_id);
    $total = count($lists);



    if(checksubmit('export_submit', true)){
        $count = $total;
        $page_limit = 2000;
        $pagesize = ceil($count/$page_limit);
        $header = array(
            'uid' => '会员UID',  'mobile' => '手机',
            'nickname' => '微信昵称','name' => '礼品名称',  'gl_id' => '当前关卡',
            'created_at'=>'创建时间'
        );
        $keys = array_keys($header);
        $html = "\xEF\xBB\xBF";
        foreach ($header as $li) {
            $html .= $li . "\t ,";
        }
        $html .= "\n";
//        for ($j = 1; $j <= $pagesize; $j++) {

            $ex_page = max(intval($_P['ex_page']),1);
            $condition = " where a.themeid=$themeid and b.status='end' ";
            if ($gl_id){
                $condition .= "  and b.gl_id=$gl_id";
            }
            if ($search_data){
                $condition .= " and c.nickname like '".$search_data."'"." or c.mobile like '".$search_data."' ";
            }
            if ($start_day && $end_day && $start_day!=$end_day){
                $condition .= "  and b.created_at between '".$start_day."' and '".$end_day."'";
            }
            $condition1 = "  order by a.created_at desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

            $sql = " select a.current_level,b.uid,b.status,b.gl_id,b.created_at,c.username,c.avatar,c.nickname,c.mobile,d.p_id,e.name,e.img from "
                .tablename(game_user_detail)." as a ".
                " left join ".tablename(game_user_level)." as b on a.uid=b.uid and a.themeid=b.themeid and a.current_level=b.gl_id+1".
                " left join ".tablename(t_fans)." as c on a.uid=c.uid and a.themeid=c.themeid ".
                " left join ".tablename(game_level)." as d on b.gl_id=d.gl_id and a.themeid=d.themeid".
                " left join ".tablename(game_prize)." as e on d.p_id=e.p_id and a.themeid=e.themeid "
                .$condition.$condition1;

            $excel_list = db_select($sql);
            if (!empty($excel_list)) {
                $size = ceil(count($excel_list) / 500);
                for ($i = 0; $i < $size; $i++) {
                    $buffer = array_slice($excel_list, $i * 500, 500);
                    foreach ($buffer as $row) {
                        $row['gl_id'] = '第'.$row['gl_id'].'关';
                        unset($info);
                        foreach ($keys as $key) {
                            $data[] = $row[$key];
                        }
                        $user[] = implode("\t ,", $data) . "\t ,";
                        unset($data);
                    }
                    $html .= implode("\n", $user)."\n";
                    unset($user);
                }
            }
        //}
        //新版本导出合并
        $is_end = 0;
        if($ex_page>=$pagesize){
            $is_end = 1;
        }
        Util::WxJump($system,$html,'用户游戏关卡记录',$themeid,$is_end,$pagesize);
    }
    $list = Game_mod::getLevelUserFlag($themeid,$search_data,$start_day,$end_day,$page_start,$page_size,$gl_id);
    $page_total = $total;
    $pager = pagination($page_total,$page_index,$page_size);
    $return_clicent = get_defined_vars();
return view('/game/level/user_list', $return_clicent);
}

if ($ac=='user_box'){
    //用户宝箱获取记录
    $total = Game_mod::getGameUserBoxFlagList($themeid,'','','','','');
    $list = Game_mod::getGameUserBoxFlagList($themeid,'','','',$page_start,$page_size);
    $page_total = count($total);
    $pager = pagination($page_total,$page_index,$page_size);

    $return_clicent = get_defined_vars();
return view('/game/level/user_list', $return_clicent);
}elseif ($ac=='user_box_search'){

    $box_user_list = Game_mod::formatBoxUserList($themeid);
    $search_data = isset($params['search_data'])?$params['search_data']:'';
    if ($search_data){
        $search_data = '%'.$search_data.'%';
    }

    $lists = Game_mod::getGameUserBoxFlagList($themeid,$search_data,$start_day,$end_day,0,0,$gb_id);
    $total = count($lists);
    if(checksubmit('export_submit', true)){
        $count = $total;
        $page_limit = 2000;
        $pagesize = ceil($count/$page_limit);
        $header = array(
            'uid' => '会员UID',  'mobile' => '手机',
            'nickname' => '微信昵称','name' => '礼品名称','box_name'=>'宝箱名称',
            'created_at'=>'创建时间'
        );
        $keys = array_keys($header);
        $html = "\xEF\xBB\xBF";
        foreach ($header as $li) {
            $html .= $li . "\t ,";
        }
        $html .= "\n";
//        for ($j = 1; $j <= $pagesize; $j++) {

            $condition = " where b.themeid=$themeid and b.is_end=1";
            if ($gb_id){
                $condition .= " and b.gb_id=$gb_id";
            }
            if ($search_data){
                $condition .= " and c.nickname like '".$search_data."'"." or c.mobile like '".$search_data."' ";
            }
            if ($start_day && $end_day && $start_day!=$end_day){
                $condition .= "  and b.created_at between '".$start_day."' and '".$end_day."'";
            }
           $ex_page = max(intval($_P['ex_page']),1);
            $condition1 = "  order by b.created_at desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

            $sql = " select b.*,c.username,c.avatar,c.nickname,c.mobile,d.name as box_name,e.question,f.name,f.img from ".
                "( select a.gub_id,a.themeid,a.uid,a.gb_id,a.p_id,a.q_id,a.created_at,a.is_end from ( select gub_id,themeid,uid,gb_id,p_id,q_id,created_at,is_end from".
                tablename(game_user_box)." order by created_at desc ) as a group by a.uid) as b".
                " LEFT JOIN ". tablename(t_fans)." as c on b.uid=c.uid and c.themeid=$themeid ".
                " LEFT JOIN ".tablename(game_box)." as d on b.gb_id=d.gb_id and d.themeid = $themeid".
                " LEFT JOIN ".tablename(game_question)." as e on b.q_id=e.q_id and e.themeid = $themeid".
                " LEFT JOIN ".tablename(game_prize)." as f on b.p_id=f.p_id and f.themeid=$themeid "
                .$condition.$condition1;

            $list = db_select($sql);
            if (!empty($list)) {
                $size = ceil(count($list) / 500);
                for ($i = 0; $i < $size; $i++) {
                    $buffer = array_slice($list, $i * 500, 500);
                    foreach ($buffer as $row) {
//                        $row['gl_id'] = '第'.$row['gl_id'].'关';
                        unset($info);
                        foreach ($keys as $key) {
                            $data[] = $row[$key];
                        }
                        $user[] = implode("\t ,", $data) . "\t ,";
                        unset($data);
                    }
                    $html .= implode("\n", $user)."\n";
                    unset($user);
                }
            }
     //   }
        //新版本导出合并
        $is_end = 0;
        if($ex_page>=$pagesize){
            $is_end = 1;
        }
        Util::WxJump($system,$html,'用户游戏关卡记录',$themeid,$is_end,$pagesize);
    }
    $list = Game_mod::getGameUserBoxFlagList($themeid,$search_data,$start_day,$end_day,$page_start,$page_size,$gb_id);
    $page_total = $total;
    $pager = pagination($page_total,$page_index,$page_size);
    $return_clicent = get_defined_vars();
return view('/game/level/user_list', $return_clicent);
}


}
}